import {
  defineComponent,
  reactive,
  DefineComponent,
  watch,
  markRaw,
} from "vue";
import { AppNavigator } from "./app-navigator";

export const AppNavigatorPage = defineComponent({
  name: "AppNavigatorPage",
  setup() {
    const state = reactive({
      PageComponent: null as null | DefineComponent,
    });

    // 通过 AppNavigator.use.inject() 就可获取 AppNavigator 组件内部定义的属性或方法
    const navigator = AppNavigator.use.inject();

    watch(
      () => navigator.state.route.path,
      async () => {
        let { path } = navigator.state.route;
        if (!path) {
          return;
        }
        if (path.charAt(0) === "/") {
          path = path.slice(1);
        }
        const Component = (await import("story/pages/" + path)).default;

        state.PageComponent = markRaw(Component);
      },
      { immediate: true }
    );

    return () => {
      const { PageComponent } = state;
      return (
        <div class="app-navigator-page">
          {!!PageComponent ? <PageComponent /> : null}
        </div>
      );
    };
  },
});
